package io.cici.cc.mybatis.lite.sql_source;

import io.cici.cc.mybatis.lite.mapping.Sql;
import io.cici.cc.mybatis.lite.mapping.SqlSource;
import io.cici.cc.mybatis.lite.session.Configuration;
import io.cici.cc.mybatis.lite.sql_source.scripting.tag.Tag;


public class DynamicSqlSource implements SqlSource {

    private final Configuration configuration;
    private final Tag tag;

    public DynamicSqlSource(Configuration configuration, Tag tag) {
        this.configuration = configuration;
        this.tag = tag;
    }

    @Override
    public Sql getSql(Object parameterObject) {
        Context context = new Context(configuration, parameterObject);
        tag.apply(context);
        SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
        Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
        SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
        Sql sql = sqlSource.getSql(parameterObject);
        context.getBindings().forEach(sql::setAdditionalParameter);
        return sql;
    }

}
